package com.cpi.cornpp.instructionspurchases.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.apache.struts.util.MessageResources;

import com.cpi.conrpp.mail.Email;
import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.instructionspurchaseforecast.form.InstructionPurchaseForecastSearchForm;
import com.cpi.cornpp.instructionspurchaseforecast.view.InstructionPurchaseForecastSearchView;
import com.cpi.cornpp.instructionspurchaseforecast.view.InstructionPurchaseForecastView;
import com.cpi.cornpp.instructionspurchases.exception.InstructionPurchaseException;
import com.cpi.cornpp.instructionspurchases.form.InstructionPurchaseForm;
import com.cpi.cornpp.instructionspurchases.form.InstructionPurchaseSearchForm;
import com.cpi.cornpp.instructionspurchases.service.InstructionPurchaseMailService;
import com.cpi.cornpp.instructionspurchases.service.InstructionPurchaseService;
import com.cpi.cornpp.instructionspurchases.view.InstructionPurchaseCreateView;
import com.cpi.cornpp.instructionspurchases.view.InstructionPurchaseSearchView;
import com.cpi.cornpp.purchaseinstructiondetail.service.InstructionPurchaseDetailService;
import com.cpi.cornpp.unit.service.UnitService;
import com.cs.common.init.SystemParameterCollection;
import com.cs.common.init.beans.SystemParameterBean;
import com.cs.common.utils.NumberUtil;

public class InstructionPurchaseAction extends MappingDispatchAction {
	private static final String DEFAULT = "default";//$NON-NLS-1$
	private final static String CUSTOM_EXCEPTION = "custom_exception";//$NON-NLS-1$
	private static final String INSTRUCTION_VIEWS = "instructionViews";//$NON-NLS-1$
	private static final String INSTRUCTION__FORECAST_VIEWS = "instructionForecastViews";//$NON-NLS-1$
	private static final String PURCHASE_INSTRUCTION_STATUS = "label.purchaseinstructiondetail.status.";//$NON-NLS-1$
	private static final String PREVIOUS_ORDER_FIELD = "previousOrderField";//$NON-NLS-1$
	private static final String PREVIOUS_ORDER_TYPE = "previousOrderType";//$NON-NLS-1$
	private static final String INSTRUCTION_PURCHASE_STATUS_OPENED_ID = "INSTRUCTION_PURCHASE_STATUS_OPENED_ID";//$NON-NLS-1$
	private static final String PURCHASE_INSTRUCTION_ID = "purchaseInstructionId";//$NON-NLS-1$
	private static final String PURCHASE_INSTRUCTION_DETAILS = "PURCHASE_INSTRUCTION_DETAILS";//$NON-NLS-1$
	private static final String HEADER_IN_SESSION_LABEL = "InstructionPurchaseCreateView";//$NON-NLS-1$
	private final static String MESSAGE = "MESSAGE";//$NON-NLS-1$
	private static final String SUCCESS_ADD_LABEL = "common.add.success";//$NON-NLS-1$
	private static final String SUCCESS_EDIT_LABEL = "common.edit.success";//$NON-NLS-1$
	private static final String INSTRUCTION_PURCHASE_STATUS_CANCELED_ID = "INSTRUCTION_PURCHASE_STATUS_CANCELED_ID";//$NON-NLS-1$
	private static final String CUSTOMER_ID_PARAMETER = "customerId";//$NON-NLS-1$
	private static final String PERIOD_ID_PARAMETER = "periodId";//$NON-NLS-1$
	private static final String PRODUCT_ID_PARAMETER = "productId";//$NON-NLS-1$
	private static final String LIST_INSTRUCTION_FORECAST_DETAIL = "LIST_INSTRUCTION_FORECAST_DETAIL";//$NON-NLS-1$
	private static final String CON_UNIT = "CON_UNIT";//$NON-NLS-1$
	private static final String CON = "CON";//$NON-NLS-1$
	private static final String SEARCH_PARAMETER = "search";//$NON-NLS-1$
	
	public ActionForward listCreate(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws InstructionPurchaseException {
		List instructionPurchaseViews = null;
		InstructionPurchaseSearchForm instructionPurchaseSearchForm = null;
		InstructionPurchaseSearchView instructionPurchaseSearchView = null;
		InstructionPurchaseService instructionPurchaseService = null;
		HttpSession httpSession = null;
		SystemParameterCollection systemParameterCollection = null;
		SystemParameterBean systemParameterBean = null;
		int orderField = 1;
		int orderType = 0;
		int purchaseStatus = 0;
		try{
			instructionPurchaseSearchView = new InstructionPurchaseSearchView();
			httpSession = request.getSession();
			instructionPurchaseSearchForm = (InstructionPurchaseSearchForm)form;
			systemParameterCollection = SystemParameterCollection.getInstance();
			systemParameterBean = systemParameterCollection.getSystemParameterBean(INSTRUCTION_PURCHASE_STATUS_OPENED_ID);
			purchaseStatus = systemParameterBean.getIntValue();
			if(instructionPurchaseSearchForm != null){
				if( instructionPurchaseSearchForm.getInstructionPurchaseSearchView() != null ){
					instructionPurchaseSearchView = instructionPurchaseSearchForm.getInstructionPurchaseSearchView();
				}
				if( instructionPurchaseSearchForm.getOrderField() > 0 ){
					orderField = instructionPurchaseSearchForm.getOrderField();
				}
				if( instructionPurchaseSearchForm.getOrderType() > 0 ){
					orderType = instructionPurchaseSearchForm.getOrderType();
				}
			}
			if( instructionPurchaseSearchForm.getInstructionPurchaseSearchView().getPurchaseStatus() == 0 ){
				instructionPurchaseSearchView.setPurchaseStatus(purchaseStatus);
			}
			instructionPurchaseSearchForm.setInstructionPurchaseSearchView(instructionPurchaseSearchView);
			instructionPurchaseService = new InstructionPurchaseService();
			instructionPurchaseViews = instructionPurchaseService.getCreateList(instructionPurchaseSearchView,orderField, (1 == orderType) ? false : true);
			setStatusDescription(instructionPurchaseViews, request);
			request.setAttribute(INSTRUCTION_VIEWS, instructionPurchaseViews);
			httpSession.setAttribute(PREVIOUS_ORDER_FIELD, Integer.toString(instructionPurchaseSearchForm.getOrderField()));
			httpSession.setAttribute(PREVIOUS_ORDER_TYPE, Integer.toString(instructionPurchaseSearchForm.getOrderType()));
			instructionPurchaseSearchForm.reset(mapping, request);
		}catch (InstructionPurchaseException instructionPurchaseException){
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionPurchaseException);
			throw instructionPurchaseException;
		}catch (Exception e){
			InstructionPurchaseException instructionPurchaseException = null;
			e.printStackTrace(System.out);
			instructionPurchaseException= new InstructionPurchaseException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_DELETE);
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionPurchaseException);
			throw instructionPurchaseException;
		}	
		return mapping.findForward(DEFAULT);
	}
	
	private void setStatusDescription(List instructionPurchaseViews, HttpServletRequest request){
		Iterator iterator = null;
		HttpSession session = null;
		MessageResources messageResources = null;
		InstructionPurchaseCreateView instructionPurchaseCreateView = null;
		String statusDescription = null;
		String statusDetailDescription = null;
		Locale userLocale = null;
		
		if( instructionPurchaseViews != null ){
			session = request.getSession();
			messageResources = getResources(request);
			iterator = instructionPurchaseViews.iterator();
			userLocale = (Locale)session.getAttribute(Globals.LOCALE_KEY);
			while(iterator.hasNext()){
				instructionPurchaseCreateView = (InstructionPurchaseCreateView)iterator.next();
				statusDescription = messageResources.getMessage(userLocale,new StringBuffer( PURCHASE_INSTRUCTION_STATUS ).append(instructionPurchaseCreateView.getPurchaseStatus()).toString());
				statusDetailDescription = messageResources.getMessage(userLocale,new StringBuffer( PURCHASE_INSTRUCTION_STATUS).append(instructionPurchaseCreateView.getPurchaseDetailStatus()).toString());
				instructionPurchaseCreateView.setPurchaseStatusDescription(statusDescription);
				instructionPurchaseCreateView.setPurchaseDetailStatusDescription(statusDetailDescription);
			}
		}
	}
	/**
	 * Action que agrega una Instruccion de Compra (Header Tabla Principal)
	 * 
	 * @author Edgar Joao
	 * 
	 * @param argMapping
	 * @param argForm
	 * @param argRequest
	 * @param argResponse
	 * @return
	 * @throws Exception
	 */
	public ActionForward goToInstructionPurchaseHeader(ActionMapping argMapping, ActionForm argForm,
			HttpServletRequest argRequest, HttpServletResponse argResponse)
			throws Exception {
		HttpSession httpSession = null;
		InstructionPurchaseForm instructionPurchaseForm = null;
		instructionPurchaseForm = (InstructionPurchaseForm) argForm;
		InstructionPurchaseCreateView instructionPurchaseCreateView = null;
		UnitService unitService = null;
		httpSession = argRequest.getSession();
		unitService = new UnitService();
		httpSession.setAttribute(CON_UNIT, String.valueOf(unitService.getUnitQuantity(CON)));
		if( instructionPurchaseForm.getFilters() != null ){
			httpSession.removeAttribute(PURCHASE_INSTRUCTION_DETAILS);
			httpSession.removeAttribute(HEADER_IN_SESSION_LABEL);
			argForm.reset(argMapping, argRequest);
		}else{
			instructionPurchaseCreateView = (InstructionPurchaseCreateView)httpSession.getAttribute(HEADER_IN_SESSION_LABEL);
			if(instructionPurchaseCreateView!=null){
				instructionPurchaseForm.getView().setComments(instructionPurchaseCreateView.getComments());
				instructionPurchaseForm.getView().setDate(instructionPurchaseCreateView.getDate());
			}
		}
		return argMapping.findForward(DEFAULT);
	}
	
	
	/**
	 * Agregar o Editar Instruccion 
	 * de Compra Header
	 * @param argMapping
	 * @param argForm
	 * @param argRequest
	 * @param argResponse
	 * @return
	 * @throws Exception
	 */
	public ActionForward addInstructionPurchaseHeader(ActionMapping argMapping, ActionForm argForm,
			HttpServletRequest argRequest, HttpServletResponse argResponse)
			throws Exception {
		
		InstructionPurchaseForm form = null;
		InstructionPurchaseService service = null;
		InstructionPurchaseMailService mailService = null;
		HttpSession httpSession = null;
		List instructionPurchaseFormDetails = null;
		String messageError = null;
		MessageResources messageResources = null;		
		Email email = null;
		
		try{
			httpSession = argRequest.getSession();
			service = new InstructionPurchaseService();
		
			form = (InstructionPurchaseForm) argForm;
			
			messageResources = getResources(argRequest);
			instructionPurchaseFormDetails = (ArrayList)httpSession.getAttribute(PURCHASE_INSTRUCTION_DETAILS);
			
			service.insertOrUpdatePurchaseInstruction(form.getView(), instructionPurchaseFormDetails);
			
			if( form.getView().getId() > 0 ){
				messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), SUCCESS_EDIT_LABEL);
				
			}else{
				messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), SUCCESS_ADD_LABEL);
				
			}
			
			if(argRequest.getParameter("sendEmail")!=null && instructionPurchaseFormDetails!=null && instructionPurchaseFormDetails.size()>0){
				mailService = new InstructionPurchaseMailService();
				Locale locale = (Locale)httpSession.getAttribute(Globals.LOCALE_KEY);
				email = mailService.buildMailForAddOrUpdateAction(form.getView(),messageResources, instructionPurchaseFormDetails, locale, form.getView().isAddAction());
				mailService.sendEmail(email);
			}
			
			httpSession.setAttribute(MESSAGE, messageError);
		}catch (InstructionPurchaseException instructionPurchaseException){
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionPurchaseException);
			throw instructionPurchaseException;
		}catch (Exception e){
			InstructionPurchaseException instructionPurchaseException = null;
			e.printStackTrace(System.out);
			instructionPurchaseException= new InstructionPurchaseException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_DELETE);
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionPurchaseException);
			throw instructionPurchaseException;
		}			
		return argMapping.findForward(DEFAULT);
	}
	/**
	 * Actualiza una Instruccion de Compra
	 * 
	 * @author Edgar Joao
	 * @param argMapping
	 * @param argForm
	 * @param argRequest
	 * @param argResponse
	 * @return
	 * @throws Exception
	 */
	public ActionForward updateInstructionPurchaseHeader(ActionMapping argMapping, ActionForm argForm,
			HttpServletRequest argRequest, HttpServletResponse argResponse)
			throws Exception {
		InstructionPurchaseForm form = null;
		InstructionPurchaseCreateView view = null;
		InstructionPurchaseService service = null;
		InstructionPurchaseDetailService instructionPurchaseDetailService = null;
		List purchaseInstructionDetailViews = null;
		HttpSession httpSession = null;
		int parameterId = 0;
		SystemParameterCollection systemParameterCollection = null;
		SystemParameterBean systemParameterCanceledBean = null;
		SystemParameterBean systemParameterOpenedBean = null;
		try{
			systemParameterCollection = SystemParameterCollection.getInstance();
			systemParameterCanceledBean = systemParameterCollection.getSystemParameterBean(INSTRUCTION_PURCHASE_STATUS_CANCELED_ID);
			systemParameterOpenedBean = systemParameterCollection.getSystemParameterBean(INSTRUCTION_PURCHASE_STATUS_OPENED_ID);
			httpSession = argRequest.getSession();
			service = new InstructionPurchaseService();
			instructionPurchaseDetailService = new InstructionPurchaseDetailService();
			form = (InstructionPurchaseForm) argForm;
			String purchaseInstructionId = (String)argRequest.getParameter(PURCHASE_INSTRUCTION_ID);
			if( purchaseInstructionId != null ){
				parameterId = Integer.parseInt(purchaseInstructionId);
				httpSession.setAttribute(PURCHASE_INSTRUCTION_ID, purchaseInstructionId);
			}else{
				parameterId = Integer.parseInt((String)httpSession.getAttribute(PURCHASE_INSTRUCTION_ID));
			}
			view = service.getInstructionPurchase(parameterId);
			purchaseInstructionDetailViews = instructionPurchaseDetailService.list(parameterId);
			argRequest.getSession().setAttribute(PURCHASE_INSTRUCTION_DETAILS , purchaseInstructionDetailViews);
			argRequest.setAttribute(INSTRUCTION_PURCHASE_STATUS_CANCELED_ID, systemParameterCanceledBean.getValue());
			argRequest.setAttribute(INSTRUCTION_PURCHASE_STATUS_OPENED_ID, systemParameterOpenedBean.getValue());
			form.setView(view);
		}catch (InstructionPurchaseException instructionPurchaseException){
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionPurchaseException);
			throw instructionPurchaseException;
		}catch (Exception e){
			InstructionPurchaseException instructionPurchaseException = null;
			e.printStackTrace(System.out);
			instructionPurchaseException= new InstructionPurchaseException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_DELETE);
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionPurchaseException);
			throw instructionPurchaseException;
		}
		return argMapping.findForward(DEFAULT);
	}

	public ActionForward query(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws InstructionPurchaseException {
		InstructionPurchaseForecastSearchForm form = null;
		InstructionPurchaseForecastSearchView view = null;
		InstructionPurchaseService service = null;
		List instructionPurchaseForecastViews = null;
		HttpSession httpSession = null;
		int orderField = 1;
		int orderType = 0;

		form = (InstructionPurchaseForecastSearchForm)actionForm;
		view = form.getInstructionPurchaseForecastSearchView();
		service = new InstructionPurchaseService();
		httpSession = request.getSession();
		String search = null;
		try {
			search = request.getParameter(SEARCH_PARAMETER);
			if( search != null && !search.equals("null") ){
				instructionPurchaseForecastViews = service.listInstructionPurchaseForecasts(view, orderField, (1 == orderType) ? false : true);
			}
			request.setAttribute(INSTRUCTION__FORECAST_VIEWS, instructionPurchaseForecastViews);
			httpSession.setAttribute(PREVIOUS_ORDER_FIELD, Integer.toString(form.getOrderField()));
			httpSession.setAttribute(PREVIOUS_ORDER_TYPE, Integer.toString(form.getOrderType()));
			if( form.getOrderField() > 0 ){
				orderField = form.getOrderField();
			}
			if( form.getOrderType() > 0 ){
				orderType = form.getOrderType();
			}
			
		} catch (InstructionPurchaseException instructionPurchaseException){
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionPurchaseException);
			throw instructionPurchaseException;
		}catch (Exception e){
			InstructionPurchaseException instructionPurchaseException = null;
			e.printStackTrace(System.out);
			instructionPurchaseException= new InstructionPurchaseException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_DELETE);
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionPurchaseException);
			throw instructionPurchaseException;
		}		
		return mapping.findForward(DEFAULT);
	}
	
	/**
	 * Metodo que muestra el
	 * Detalle Pronostico de Ventas
	 * 
	 * @author Edgar Joao
	 * @param argMapping
	 * @param argForm
	 * @param argRequest
	 * @param argResponse
	 * @return
	 * @throws Exception
	 */
	public ActionForward goToPurchaseForecastDetail(ActionMapping argMapping, ActionForm argForm, HttpServletRequest argRequest, HttpServletResponse argResponse) throws Exception {
		List instructionForecastDetailList = null;
		Iterator iterator = null;
		HttpSession httpSession = null;						
		InstructionPurchaseService service = null;		
		httpSession = argRequest.getSession();
		String periodId   = null;
		String customerId = null;		
		String productId  = null;		
		InstructionPurchaseForecastView view = null;
		StringBuffer customer = null;
		StringBuffer item = null;
		try{
			service = new InstructionPurchaseService();
			instructionForecastDetailList = new ArrayList(0);
			customerId = (String) argRequest.getParameter(CUSTOMER_ID_PARAMETER);
			periodId   = (String) argRequest.getParameter(PERIOD_ID_PARAMETER);
			productId  = (String) argRequest.getParameter(PRODUCT_ID_PARAMETER);
			instructionForecastDetailList = service.getInstructionForecastDetail(NumberUtil.parseInt(periodId), customerId, productId);
			argRequest.setAttribute(LIST_INSTRUCTION_FORECAST_DETAIL, instructionForecastDetailList);
			view = new InstructionPurchaseForecastView();
			iterator = instructionForecastDetailList.iterator();
			if(iterator.hasNext()){
				view = (InstructionPurchaseForecastView) iterator.next(); 
			}
			customer = new StringBuffer(0);
			customer.append(view.getCustomerId());
			customer.append(" - ");
			customer.append(view.getCustomerDescription());
			item = new StringBuffer(0);
			item.append(view.getItemId());
			item.append(" - ");
			item.append(view.getItemDescription());
			argRequest.setAttribute("CUSTOMER",customer.toString());
			argRequest.setAttribute("ITEM",item.toString());
			argRequest.setAttribute("PERIOD",String.valueOf(view.getYear()));
			
		} catch (InstructionPurchaseException instructionPurchaseException){
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionPurchaseException);
			throw instructionPurchaseException;
		}catch (Exception e){
			InstructionPurchaseException instructionPurchaseException = null;
			e.printStackTrace(System.out);
			instructionPurchaseException= new InstructionPurchaseException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_DELETE);
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionPurchaseException);
			throw instructionPurchaseException;
		}						
		return argMapping.findForward(DEFAULT);
	}

}